package com.cyn.chat.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.cyn.chat.service.GptSerivce;
import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.completion.CompletionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


@Service
public class GptServiceImpl implements GptSerivce {
    @Value("${open.ai.model}")
    private String openAiModel;
    @Autowired
    private OpenAiService openAiService;
    private String context; // 上下文变量

    @Override
    public String chat(String message) {
        String proxyHost = "127.0.0.1";
        int proxyPort = 7891;
        // 设置代理
        System.setProperty("http.proxyHost", proxyHost);
        System.setProperty("http.proxyPort", Integer.toString(proxyPort));
        System.setProperty("https.proxyHost", proxyHost);
        System.setProperty("https.proxyPort", Integer.toString(proxyPort));

        // 设置请求
        CompletionRequest completionRequest;
        if (StrUtil.isBlank(context)) {
            // 如果上下文为空，则只使用当前的问题
            completionRequest = CompletionRequest.builder()
                    .prompt(message)
                    .model(openAiModel)
                    .echo(true)
                    .temperature(0.7)
                    .topP(1d)
                    .frequencyPenalty(0d)
                    .presencePenalty(0d)
                    .maxTokens(1000)
                    .build();
        } else {
            // 如果上下文不为空，则将之前的问题和当前的问题拼接
            completionRequest = CompletionRequest.builder()
                    .prompt(context + "\n" + message)
                    .model(openAiModel)
                    .echo(true)
                    .temperature(0.7)
                    .topP(1d)
                    .frequencyPenalty(0d)
                    .presencePenalty(0d)
                    .maxTokens(1000)
                    .build();
        }

        // 获取回答
        CompletionResult completionResult = openAiService.createCompletion(completionRequest);
        String text = completionResult.getChoices().get(0).getText();

        // 更新上下文
        context = updateContext(context, message, text);

        // 截取最终答案部分
        String textResponse = getTextResponse(text);

        // 返回本次回答的内容
        return textResponse;
    }

    private String getTextResponse(String text) {
        String[] responses = text.split("\n");

        // 只返回最后一个非空回答
        String lastResponse = "";
        for (int i = responses.length - 1; i >= 0; i--) {
            if (!responses[i].trim().isEmpty() && !responses[i].endsWith("？")) {
                lastResponse = responses[i].trim();
                break;
            }
        }
        return lastResponse;
    }

    public String updateContext(String context, String message, String response) {
        // 如果之前的回答不为空，将其与当前的问题和回答拼接起来作为新的上下文
        if (StrUtil.isNotBlank(context)) {
            return context + "\n" + message + "\n" + response;
        }
        // 如果之前的回答为空，直接返回当前的问题和回答作为新的上下文
        return message + "\n" + response;
    }
}